package com.hitqz.robot.strategy;

import com.google.common.util.concurrent.RateLimiter;
import com.hitqz.robot.dto.AirQualityDto;
import com.hitqz.robot.netty.message.ChipMessage;
import com.hitqz.robot.util.ChipCacheUtil;
import com.hitqz.robot.util.ChipToolKit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xupkun
 * @date 2024/11/3
 */
@Slf4j
public class Chip2BStrategy implements ChipMessageHandlerStrategy{

    private static final RateLimiter logLimiter = RateLimiter.create(1);

    @Override
    public void handle(ChannelHandlerContext ctx, ChipMessage message) {
        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
        String ipAddress = ipSocket.getAddress().getHostAddress();
        byte[] data = message.getData();
        byte mainCmd = data[0];
        byte subCmd = data[1];
        // 分配 ByteBuf 并将数据写入
        ByteBuf buffer = ctx.alloc().buffer(data.length);
        buffer.writeBytes(data);
        try {
            mainCmd = buffer.readByte();
            subCmd = buffer.readByte();
            if (subCmd == 0x02) {
                Map<String ,Object> ret = (Map<String, Object>) ChipCacheUtil.get(ChipCacheUtil.KEY_AIR_QUALITY);
                if (ret  == null) {
                    ret = new HashMap<>();
                }
                byte result = buffer.readByte();
                short pm2Point5 = buffer.readShortLE();
                short tvoc = buffer.readShortLE();//tvoc数据
                short smoke = buffer.readShortLE();//烟雾数据（0：没有；1有）
                short temperature = buffer.readShortLE();//温度
                short humidity = buffer.readShortLE();//湿度
                short alcohol = buffer.readShortLE();//酒精
                short h2s = buffer.readShortLE();//硫化氢
                short nh = buffer.readShortLE();//氨气
                short noise = buffer.readShortLE();//噪音
                short pm10 = buffer.readShortLE();//pm10
//                short ch4 = buffer.readShortLE();//ch4
//                short gas = buffer.readShortLE();//可燃气体
                if (logLimiter.tryAcquire(60)){
                    log.info("[chip]2B02 air:pm2.5{},tvoc:{},smoke:{},temperature:{},humidity:{},alcohol:{},h2s:{},nh:{},noise:{},pm10:{},ch4:{},gas:{}", pm2Point5, tvoc, smoke, temperature, humidity, alcohol, h2s, nh, noise, pm10);
                }
                // 保存返回
                AirQualityDto airQualityDto = AirQualityDto.builder().
                        pm2Point5(pm2Point5).tvoc(tvoc).smoke(smoke).
                        temperature(temperature).humidity(humidity).alcohol(alcohol).h2s(h2s).nh(nh).noise(noise).pm10(pm10).build();
                ret.put(ipAddress, airQualityDto);
                ChipCacheUtil.put(ChipCacheUtil.KEY_AIR_QUALITY, ret);
                // todo 报警

            }
            ChipToolKit.release(message, true, true);
        } catch (Exception e) {
            log.error("[chip]deal  {}{}-message error,{}",String.format("%02x",mainCmd),String.format("%02x",subCmd),e.getMessage());
        } finally {
            // 确保 ByteBuf 在使用完后释放，防止内存泄漏
            buffer.release();
        }


    }
}

